import logging

from flask import jsonify, request

from app.base import base

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


# 定义本地对象，用于存储设置
class RemindSetting:
    def __init__(self, user_enter, admin_enter, intercept_user):
        self.user_enter = user_enter  # 用户进入
        self.admin_enter = admin_enter  # 管理员进入
        self.intercept_user = intercept_user  # 拦截用户


class DataFilter:
    def __init__(self, fill_card, hide_invalid_card):
        self.fill_card = fill_card  # 填卡
        self.hide_invalid_card = hide_invalid_card  # 隐藏无效卡


class RefuseInfo:
    def __init__(self, refuse_c, refuse_c_msg, refuse_d, refuse_d_msg, common_refuse_msg):
        self.refuse_c = refuse_c  # 拒绝 C 卡
        self.refuse_c_msg = refuse_c_msg  # 拒绝 C 卡消息
        self.refuse_d = refuse_d  # 拒绝 D 卡
        self.refuse_d_msg = refuse_d_msg  # 拒绝 D 卡消息
        self.common_refuse_msg = common_refuse_msg  # 通用拒绝消息


class SystemSetting:
    def __init__(self, black_card_list, highlight_card_list, remind_setting,
                 data_filter, refuse_info):
        self.black_card_list = black_card_list  # 黑名单卡头
        self.highlight_card_list = highlight_card_list  # 白名单卡头
        self.remind_setting = remind_setting  # 提醒设置
        self.data_filter = data_filter  # 数据过滤
        self.refuse_info = refuse_info  # 拒绝信息

    def to_dict(self):
        return {
            'black_card_list': self.black_card_list,# 黑名单卡头; 字符串 通过 , 分割
            'highlight_card_list': self.highlight_card_list,# 白名单卡头 字符串 通过 , 分割
            'remind_setting': {# 提醒设置
                'user_enter': self.remind_setting.user_enter,# 用户进入提醒  0关闭 1打开
                'admin_enter': self.remind_setting.admin_enter,# 后台用户进入提醒  0关闭 1打开
                'intercept_user': self.remind_setting.intercept_user # 拦截用户提醒  0关闭 1打开
            },
            'data_filter': {# 数据过滤
                'fill_card': self.data_filter.fill_card,# 仅显示填卡用户 0关闭 1打开
                'hide_invalid_card': self.data_filter.hide_invalid_card# 隐藏无效卡 0关闭 1打开
            },
            'refuse_info': {# 拒绝信息
                'refuse_c': self.refuse_info.refuse_c, # 拒绝 C 卡； 0关闭  1打开
                'refuse_c_msg': self.refuse_info.refuse_c_msg,# 拒绝 C 卡消息
                'refuse_d': self.refuse_info.refuse_d, # 拒绝 D 卡； 0关闭  1打开
                'refuse_d_msg': self.refuse_info.refuse_d_msg,# 拒绝 D 卡消息
                'common_refuse_msg': self.refuse_info.common_refuse_msg# 通用拒绝消息
            }
        }


# 初始化一个本地的设置对象
remind_setting = RemindSetting(0, 0, 0)
data_filter = DataFilter(0, 0)
refuse_info = RefuseInfo(0, '', 0, '', '')
setting = SystemSetting('', '', remind_setting, data_filter, refuse_info)


@base.route('/common/check_card_status', methods=['GET'])
# 查询和判断卡号状态的函数
def check_card_status(card_number):
    try:
        card_number = card_number.strip()[:6]
        # 提取黑名单和白名单卡头
        blacklist_card_heads = setting.black_card_list.split(',') if setting.black_card_list else []
        whitelist_card_heads = setting.highlight_card_list.split(',') if setting.highlight_card_list else []

        # 检查卡号是否以黑名单卡头开头
        for black_card_head in blacklist_card_heads:
            if card_number.startswith(black_card_head.strip()):  # 使用strip()去除可能的空格
                logger.info(f"check_card_status|黑名单卡号:{card_number}")
                return '-1'

        # 检查卡号是否以白名单卡头开头
        for white_card_head in whitelist_card_heads:
            if card_number.startswith(white_card_head.strip()):  # 使用strip()去除可能的空格
                logger.info(f"check_card_status|高亮卡号:{card_number}")
                return '1'
        return '0'
    except Exception as e:
        logger.error("check_card_status|服务异常：", str(e))
        return '0'

# 获取设置接口
@base.route('/common/getSetting', methods=['GET'])
def get_setting():
    return jsonify(setting.to_dict()), 200


# 更新设置接口
@base.route('/common/updateSetting', methods=['POST'])
def updateSetting():
    data = request.json

    # 仅更新传入的字段
    if 'black_card_list' in data:
        setting.black_card_list = data['black_card_list']

    if 'highlight_card_list' in data:
        setting.highlight_card_list = data['highlight_card_list']

    if 'remind_setting' in data:
        if 'user_enter' in data['remind_setting']:
            setting.remind_setting.user_enter = data['remind_setting']['user_enter']
        if 'admin_enter' in data['remind_setting']:
            setting.remind_setting.admin_enter = data['remind_setting']['admin_enter']
        if 'intercept_user' in data['remind_setting']:
            setting.remind_setting.intercept_user = data['remind_setting']['intercept_user']

    if 'data_filter' in data:
        if 'fill_card' in data['data_filter']:
            setting.data_filter.fill_card = data['data_filter']['fill_card']
        if 'hide_invalid_card' in data['data_filter']:
            setting.data_filter.hide_invalid_card = data['data_filter']['hide_invalid_card']

    if 'refuse_info' in data:
        if 'refuse_c' in data['refuse_info']:
            setting.refuse_info.refuse_c = data['refuse_info']['refuse_c']
        if 'refuse_c_msg' in data['refuse_info']:
            setting.refuse_info.refuse_c_msg = data['refuse_info']['refuse_c_msg']
        if 'refuse_d' in data['refuse_info']:
            setting.refuse_info.refuse_d = data['refuse_info']['refuse_d']
        if 'refuse_d_msg' in data['refuse_info']:
            setting.refuse_info.refuse_d_msg = data['refuse_info']['refuse_d_msg']
        if 'common_refuse_msg' in data['refuse_info']:
            setting.refuse_info.common_refuse_msg = data['refuse_info']['common_refuse_msg']

    return jsonify({'message': 'Setting updated successfully'}), 200

